package custom;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import java.lang.ref.WeakReference;

import constants.Constants;
import constants.HandlerConstant;
import customhandler.MyHandler;
import singleton.SingletonClass;

/**
 * Created by admin on 2017/10/30.
 */
public class MyDialog extends Dialog {
    private FrameHandler mHandler;

    public MyDialog(@NonNull Context context) {
        super(context);
    }

    public MyDialog(@NonNull Context context, int themeResId) {
        super(context, themeResId);

    }

    protected MyDialog(@NonNull Context context, boolean cancelable, @Nullable OnCancelListener cancelListener) {
        super(context, cancelable, cancelListener);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        Looper.prepare();
        mHandler = new FrameHandler(this);
//        setCancelable(false);
//        setCanceledOnTouchOutside(false);
        // 旧安卓版不需要
    }


    protected void sendFrameMessage(Message msg) {
        mHandler.sendMessage(msg);
    }

    //处理信息
    public void onHandleFrameMessage(Message msg) {
    }

    protected void sendEmptyFrameMessage(int what) {
        mHandler.sendEmptyMessage(what);
    }
    protected void sendEmptyFrameMessageDelay(int what,long delayMillis) {
        mHandler.sendEmptyMessageDelayed(what,delayMillis);
    }

    /**
     * 处理Activity上消息的Handler
     */
    public static class FrameHandler extends Handler {

        private WeakReference<MyDialog> contexts;

        public FrameHandler(MyDialog baseThread) {
            contexts = new WeakReference<MyDialog>(baseThread);
            SingletonClass.getSingleton(MyHandler.class).registeHandler(this);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (contexts != null) {
                MyDialog baseThread = contexts.get();
                if (baseThread != null) {
                    try {
                        baseThread.onHandleFrameMessage(msg);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
